<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="方案" prop="planId">
        <el-input
          style="width: 100px"
          v-model="queryParams.planId"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="交易对" prop="instId">
        <el-input
          v-model="queryParams.instId"
          placeholder="请输入交易对"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据维度" prop="bar">
        <el-input
          v-model="queryParams.bar"
          placeholder="请输入数据维度"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="观测时间">
        <el-date-picker
          v-model="daterangeGcTime"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateRangeChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="账号用户" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入账号用户"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 统计信息显示区域 -->
    <div class="statistics-panel" v-if="displayStats && displayStats !== '--'">
      <div class="stat-item"><label>统计预览: <span v-html="displayStats"></span></label></div>
    </div>

    <el-table v-loading="loading" :data="successList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <!-- 账号信息合并列 -->
      <el-table-column label="账号信息" align="center" >
        <template slot-scope="scope">
          <div style="text-align: center; line-height: 1.5;">
            <div style="text-align: left; display: inline-block; line-height: 1.5;">
              <div >账号:{{ scope.row.accName }} <span style="color: red;">案[{{ scope.row.planId }}]</span></div>
              <div >用户{{ scope.row.userName }}</div>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 交易对信息合并列 -->
      <el-table-column label="币种信息" align="center" >
        <template slot-scope="scope">
          <div style="text-align: center; line-height: 1.5;">
            <div style="text-align: left; display: inline-block; line-height: 1.5;">
              <div >币种:{{ formatInstId(scope.row.instId) }} [{{ scope.row.bar }}-{{ scope.row.monitorYz }}]</div>
              <div >观测:{{ scope.row.gcTime }}</div>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 价格信息合并列 -->
      <el-table-column label="价格信息" align="center" >
        <template slot-scope="scope">
          <div style="text-align: center; line-height: 1.5;">
            <div style="text-align: left; display: inline-block; line-height: 1.5;">
              <div >开仓:{{ scope.row.openAvgPx }} 平仓:{{ scope.row.closeAvgPx }} </div>
              <div >止盈:{{ scope.row.tpTriggerPx }} 止损:{{ scope.row.slTriggerPx }} </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 时间快照合并列 -->
      <el-table-column label="时间快照" align="center" >
        <template slot-scope="scope">
          <div style="text-align: center; line-height: 1.5;">
            <div style="text-align: left; display: inline-block; line-height: 1.5;">
              <div >开仓:{{ scope.row.openTime }}</div>
              <div >平仓:{{ scope.row.closeTime }}</div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="收益信息" align="center" >
        <template slot-scope="scope">
          <div style="text-align: center; line-height: 1.5;">
            <div style="text-align: left; display: inline-block; line-height: 1.5;">
              <div>收益: <span v-if="scope.row.realizedPnl > 0" style="color: green;">赚:</span><span v-else style="color: red;">亏:</span>{{ scope.row.realizedPnl }} <span style="color: red;">|</span>
                {{ scope.row.side === 'buy' ? '做多' : '做空' }} <span style="color: red;">|</span>{{ scope.row.sz }}</div>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 合并后的状态信息列 -->
      <el-table-column label="状态信息" align="center">
        <template slot-scope="scope">
          <div style="text-align: center; line-height: 1.5;">
            <div>订单状态: <dict-tag :options="dict.type.order_close_state" :value="scope.row.updateState" style="display: inline-block;"/></div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="下单规则" align="center"  width="300">
        <template slot-scope="scope">
          <div style="text-align: center; line-height: 1.5;">
            <div style="text-align: left; display: inline-block; line-height: 1.5;">
              <div >{{ scope.row.tradeMsg }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listSuccess, getSuccess, delSuccess, addSuccess, updateSuccess } from "@/api/bussiness/success"
import {selectTotal} from "@/api/bussiness/success";

export default {
  name: "Success",
  dicts: ['order_close_state', 'wait_order_state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 成交订单表格数据
      successList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 数据添加时间时间范围
      daterangeGcTime: [],
      // 数据添加时间时间范围
      daterangeAddTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planId: null,
        instId: null,
        bar: null,
        gcTime: null,
        updateState: null,
        userName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      totalData: [], // 用来存放 selectTotal 接口返回的数据，改为数组
      displayStats: '--' // 用于显示的统计信息字符串
    }
  },
  created() {
    this.setDefaultDateRange()
    this.getList()
    this.selectTotal() // 初始化时也调用统计接口
  },
  methods: {
    /** 设置默认日期范围 - 当前前一天到今日 */
    setDefaultDateRange() {
      const now = new Date()
      const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)

      // 格式化开始日期为 yyyy-MM-dd 08:00:00
      const formatStartDate = (date) => {
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        return `${year}-${month}-${day} 08:00:00`
      }

      // 格式化结束日期为 yyyy-MM-dd 23:59:59
      const formatEndDate = (date) => {
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        return `${year}-${month}-${day} 23:59:59`
      }

      // 设置默认日期范围
      this.daterangeGcTime = [
        formatStartDate(yesterday),
        formatEndDate(now)
      ]
    },

    /** 处理日期范围变化 */
    handleDateRangeChange() {
      if (this.daterangeGcTime && this.daterangeGcTime.length === 2) {
        // 格式化开始日期为 yyyy-MM-dd 08:00:00
        const formatStartDate = (dateStr) => {
          const date = new Date(dateStr)
          const year = date.getFullYear()
          const month = (date.getMonth() + 1).toString().padStart(2, '0')
          const day = date.getDate().toString().padStart(2, '0')
          return `${year}-${month}-${day} 08:00:00`
        }

        // 格式化结束日期为 yyyy-MM-dd 23:59:59
        const formatEndDate = (dateStr) => {
          const date = new Date(dateStr)
          const year = date.getFullYear()
          const month = (date.getMonth() + 1).toString().padStart(2, '0')
          const day = date.getDate().toString().padStart(2, '0')
          // return `${year}-${month}-${day} 23:59:59`
          return `${year}-${month}-${day} 07:59:59`
        }

        // 更新日期范围，确保时间部分正确
        this.daterangeGcTime = [
          formatStartDate(this.daterangeGcTime[0]),
          formatEndDate(this.daterangeGcTime[1])
        ]
      }
    },

    /** 查询成交订单列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeGcTime && '' != this.daterangeGcTime) {
        this.queryParams.params["beginGcTime"] = this.daterangeGcTime[0]
        this.queryParams.params["endGcTime"] = this.daterangeGcTime[1]
      }
      if (null != this.daterangeAddTime && '' != this.daterangeAddTime) {
        this.queryParams.params["beginAddTime"] = this.daterangeAddTime[0]
        this.queryParams.params["endAddTime"] = this.daterangeAddTime[1]
      }
      listSuccess(this.queryParams).then(response => {
        this.successList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        accName: null,
        accCode: null,
        instId: null,
        bar: null,
        algoId: null,
        sz: null,
        side: null,
        triggerPx: null,
        zysyl: null,
        tpTriggerPx: null,
        zssyl: null,
        slTriggerPx: null,
        realizedPnl: null,
        fee: null,
        tradeMsg: null,
        openAvgPx: null,
        closeAvgPx: null,
        gcTime: null,
        gcTimePrice: null,
        openTime: null,
        closeTime: null,
        pnlRatio: null,
        monitorYz: null,
        updateState: null,
        userName: null,
        addTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
      this.selectTotal() // 搜索时调用统计接口
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 重置观测时间范围
      this.setDefaultDateRange()
      this.daterangeAddTime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加成交订单"
    },
    /** 格式化币种显示，去掉-USDT-SWAP */
    formatInstId(instId) {
      if (!instId) return ''
      return instId.replace('-USDT-SWAP', '')
    },

    /** 调用selectTotal接口获取统计信息 */
    selectTotal() {
      const params = {
        ...this.queryParams,
        params: this.queryParams.params
      }
      // 使用导入的 selectTotal 方法
      selectTotal(params).then(res => {
        this.totalData = res;
        // 处理统计数据显示
        this.formatStatsDisplay();
      }).catch(error => {
        console.error('获取统计信息失败:', error)
        this.$modal.msgError("获取统计信息失败")
        this.displayStats = '--'
      })
    },

    /** 格式化统计数据显示 */
    formatStatsDisplay() {
      if (!this.totalData || this.totalData.length === 0) {
        this.displayStats = '--'
        return
      }

      // 使用for循环拼接字符串
      let result = '';
      for (let i = 0; i < this.totalData.length; i++) {
        const item = this.totalData[i];
        result += `方案${item['方案编号']} 收益${item['最终收益']}`;

        // 如果不是最后一个元素，添加红色竖线
        if (i < this.totalData.length - 1) {
          result += '<span style="color: red;">|</span>';
        }
      }

      this.displayStats = result;
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('bussiness/success/export', {
        ...this.queryParams
      }, `success_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.statistics-panel {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 2px;
}

.statistics-panel .stat-item {
  display: block;
  margin-bottom: 10px;
  font-size: 15px;
}
</style>
